<?php
namespace app\common\service\WeChat;
use app\common\model\Store;
use app\common\service\JwtAuth;
use app\user\model\UserModel;

class Mini
{
    public $config = [
//            'token'          => 'test',
//            'encodingaeskey' => 'BJIUzE0gqlWy0GxfPp4J1oPTBmOrNDIGPNav1YFH5Z5',
        'appid'          => 'wxe44635c633795dd2',
        'appsecret'      => '6eb54b5dc4ae258d7084ed921d41b8b8',
//            // 配置商户支付参数（可选，在使用支付功能时需要）
//        'mch_id'         => "",
//        'mch_key'        => '',
//            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
//            'ssl_key'        => '',
//            'ssl_cer'        => '',
//            // 缓存目录配置（可选，需拥有读写权限）
//            'cache_path'     => '',
    ];
    public function __construct()
    {
        include env('extend_path') . "WeChatDeveloper/include.php";
    }
    public function code2SessionAndOpenid($code, $store_code)
    {
        $app = new \WeMini\Crypt($this->config);
        $session = $app->session($code);
//        var_dump($session);die;
//        array(2) {
//           ["session_key"]=> string(24) "Gq07Ajve9kFeh9ahd2fPaQ=="
//           ["openid"]=> string(28) "oMC_j5KIWi-dq92_nvwM3sh9Mn1I"
//        }
        $sid = $this->saveSessionKey($session);
        $profile = UserModel::findOrCreateByWxOpenId($session['openid']); // 判断是否已经注册，如果没有注册则新增
        $token = $this->createToken([
            'id' => $profile['id'],
            'status' => $profile['status'],
//            'store_id' => Store::where('code', $store_code)->value('id')
        ]);
        $userInfo = [
            'code' => $profile['id'],
            'avatarUrl' => $profile['avatar'],
            'nickName' => $profile['nickname'],
        ];
        // 没有token就是没有档案
        return compact('sid','token', 'userInfo');
    }
    private function saveSessionKey($session)
    {
        $sid = makeSn();
        $res = db('wx_session')->insert([
            'sid' => $sid,
            'openid' => $session['openid'],
            'unionid' => isset($session['unionid']) ? $session['unionid'] : '',
            'session_key' => $session['session_key'],
            'expire_time' => date('Y-m-d H:i:s', time() + 3600),
            'add_time' => now(),
        ]);
        if($res == false) exception('保存session失败');
        return $sid;
    }
    private function createToken($payload)
    {
        return JwtAuth::getToken($payload);
    }
    public function makeStoreQrcode($store_code)
    {
        $app = new \WeMini\Qrcode($this->config);
//        $image = $app->createMiniScene($store_code, 'pages/authorize');
        $image = $app->createMiniPath('pages/authorize?code=' . $store_code);
        return base64_encode($image);
    }

}